package main

import (
	"errors"
	"fmt"
	//"strings"
	//"strconv"
)

//作业10 实现字符串替换函数
func main() {
	sText := "hello 你好"
	ss, _ := MyReplace(sText, "he", "你好")
	fmt.Println(ss)
}

//获取包含该字符串次数
func GetMyContainsNum(s string, sub string) (int, error) {
	var istrue = false
	var num = 0
	sarr := []byte(s)
	subarr := []byte(sub)
	var err error
	if len(subarr) > len(sarr) {
		err = errors.New("此字符串内不包含该字符串")
	} else {
		for i := 0; i < len(sarr)-len(subarr); i++ {
			if sarr[i] == subarr[0] {
				for j := 0; j < len(subarr); j++ {
					if sarr[i+j] != subarr[j] {
						istrue = false
						break
					}
					istrue = true
				}
				if istrue {
					num++
				}
			}
		}
	}
	return num, err
}

//查看是否包含此字符串
func MyContains(s string, sub string) bool {
	var istrue bool
	num, err := GetMyContainsNum(s, sub)

	if err != nil {
		istrue = false
	} else if num > 0 {
		istrue = true
	} else {
		istrue = false
	}

	return istrue
}

//替换字符串
func MyReplace(old string, nead string, th string) (string, error) {
	var err error
	oldarr := []byte(old)
	neadarr := []byte(nead)
	tharr := []byte(th)
	var newarr []byte
	istrue := false
	if MyContains(old, nead) {
		for i := 0; i < len(oldarr); i++ {
			if oldarr[i] == neadarr[0] {
				for j := 0; j < len(neadarr); j++ {
					if oldarr[i+j] != neadarr[j] {
						istrue = false
						break
					}
					istrue = true
				}
				if istrue {
					for j := 0; j < len(tharr); j++ {
						newarr = append(newarr, tharr[j])
					}
					i = i + len(neadarr)
				}
			}
			newarr = append(newarr, oldarr[i])
		}
	} else {
		err = errors.New("此字符串内不包含该字符串")
	}
	old = string(newarr)
	return old, err
}
